//
//  HomeMainViewController.m
//  ArtDog
//
//  Created by dllo on 16/8/27.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "HomeMainViewController.h"
#import "BaseCollectionView.h"
#import "ShufView.h"
#import "HLMacro.h"
#import "ZWYNetTool.h"
#import "NSString+Common.h"
#import "MJRefresh.h"
#import "MJRefreshComponent+RefreshStyle.h"

// Controller
#import "HomeBannerDetailsController.h"
#import "HomeExhibitViewController.h"
#import "HomeWorksViewController.h"
#import "HomeArtistViewController.h"
#import "HomeReadViewController.h"
#import "DetailsWebViewController.h"
#import "TopicHeadMoreViewController.h"
#import "GalleryHeadMoreViewController.h"
#import "ExhibitHeadMoreViewController.h"
#import "ExhibitWorkHeadMoreViewController.h"

// Cell
#import "BannerCollectionViewCell.h"
#import "HalfImageAndWordsCollectionCell.h"
#import "HomeSpecialCollectionCell.h"
#import "HomeLabelListCell.h"
#import "HeadReusableView.h"

// Model
#import "HomeBannerModel.h"
#import "HomeMainModel.h"
#import "HomeTopicList.h"
#import "HomeExhibitList.h"
#import "HomeExhibitWorkList.h"
#import "ExhibitWorkCollectionCell.h"
#import "HomeLabelList.h"
#import "HomeGalleryList.h"
#import "ExhibitDetailsViewController.h"
#import "ExhibitWorkDetailsViewController.h"



@interface HomeMainViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, ShufViewDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) NSMutableArray<HomeBannerModel *> *bannerArray;

@property (nonatomic, strong) NSArray *headArray;

@property (nonatomic, strong) HomeMainModel *mainModel;

@property (nonatomic, assign) CGFloat lastContentOffset;

@property (nonatomic, assign) NSUInteger pageIndex;

@property (nonatomic, strong) NSMutableArray *lastSectionArray;

@end

@implementation HomeMainViewController

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    self.hidesBottomBarWhenPushed = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = YES;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self handleBannerData];
    [self handleHomeData];
    [self setupNavigationBar];
    [self createCollectionView];
    [self refreshCollectionView];
    self.isHaveActivity = YES;
}

- (void)handleBannerData
{
    self.tabBarController.tabBar.hidden = NO;
    [(MJRefreshAutoNormalFooter *)_collectionView.mj_footer setTitle:@"数据正在加载中，请稍等" forState:MJRefreshStateIdle];
    NSString *urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"home/getHomeBanner"] andParams:@{@"token": [NSString getUserDefaultToken]}];
    [ZWYNetTool GET:urlString andBody:nil andHeader:HOSTHEADER andResponse:ZWYJSON andSuccessBlock:^(id result) {
        _bannerArray = [NSMutableArray array];
        for (NSDictionary *dic in result[@"data"]) {
            HomeBannerModel *bannerModel = [HomeBannerModel modelWithDic:dic];
            [_bannerArray addObject:bannerModel];
        }
        self.isHaveActivity = NO;
        [_collectionView reloadData];
        
    } andFailureBlock:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

- (void)handleHomeData
{
    _pageIndex = 1;
    NSString *urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"home/v4/indexHome"] andParams:@{@"token": [NSString getUserDefaultToken], @"pageIndex": [NSString stringWithFormat:@"%ld", (unsigned long)_pageIndex]}];
    [ZWYNetTool GET:urlString andBody:nil andHeader:HOSTHEADER andResponse:ZWYJSON andSuccessBlock:^(id result) {
        _lastSectionArray = [NSMutableArray array];
        _mainModel = [HomeMainModel modelWithDic:result[@"data"]];
        _headArray = @[@"悦读", @"专题", @"逛展", @"赏析"];
        _lastSectionArray = _mainModel.exhibitWorkList.mutableCopy;
        [_collectionView reloadData];
        [_collectionView.mj_header endRefreshing];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"%@", error);
        [_collectionView.mj_header endRefreshing];
    }];
}

- (void)handleLastSectionData
{
    
    NSString *urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"home/v4/indexHome"] andParams:@{@"token": [NSString getUserDefaultToken], @"pageIndex": [NSString stringWithFormat:@"%ld", (unsigned long)_pageIndex]}];
    [ZWYNetTool GET:urlString andBody:nil andHeader:HOSTHEADER andResponse:ZWYJSON andSuccessBlock:^(id result) {
        NSArray *array = result[@"data"][@"exhibitWorkList"];
        for (NSDictionary *dic in array) {
            HomeExhibitWorkList *exhibitWork = [HomeExhibitWorkList modelWithDic:dic];
            [_lastSectionArray addObject:exhibitWork];
        }
        [_collectionView reloadData];
        
        [(MJRefreshAutoNormalFooter *)_collectionView.mj_footer setTitle:@"已经全部加载完毕" forState:MJRefreshStateIdle];
        [_collectionView.mj_footer endRefreshing];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"%@", error);
        [_collectionView.mj_footer endRefreshing];
    }];
}

- (void)setupNavigationBar
{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"icon_search"] style:UIBarButtonItemStylePlain target:self action:@selector(searchAction:)];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
}

/** 创建CollectionView */
- (void)createCollectionView
{
    //[_collectionView.mj_header beginRefreshing];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    _collectionView = [[BaseCollectionView alloc]initWithFrame:CGRectMake(0, -64, SCREEN_WIDTH, SCREEN_HEIGHT - 49) collectionViewLayout:flowLayout];
    [self.view addSubview:_collectionView];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    [_collectionView registerClass:[HeadReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headReusableView"];
    [_collectionView registerNib:[UINib nibWithNibName:@"BannerCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"bannerCollectionViewCell"];
    [_collectionView registerNib:[UINib nibWithNibName:@"HomeLabelListCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"homeLabelListCell"];
    [_collectionView registerNib:[UINib nibWithNibName:@"HalfImageAndWordsCollectionCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"halfImageAndWordsCollectionCell"];
    [_collectionView registerNib:[UINib nibWithNibName:@"HomeSpecialCollectionCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"homeSpecialCollectionCell"];
    [_collectionView registerNib:[UINib nibWithNibName:@"ExhibitWorkCollectionCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"exhibitWorkCollectionCell"];
}

- (void)searchAction:(UIBarButtonItem *)barButton
{
    
}

#pragma mark - 刷新
- (void)refreshCollectionView
{
    _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self handleBannerData];
        [self handleHomeData];
    }];
    [_collectionView.mj_header mjRefreshStateHeaderStyle];
    
    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _pageIndex++;
        _lastContentOffset = CGFLOAT_MAX;
        [self handleLastSectionData];
    }];
    [_collectionView.mj_footer mjRefreshAutoStateFooterStyle];
}

#pragma mark - collectionView 协议方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return _headArray.count + 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return _mainModel.labelList.count;
    } else if (section == 2) {
        return _mainModel.topicList.count;
    } else if (section == 3) {
        return _mainModel.galleryList.count;
    } else if (section == 4) {
        return _mainModel.exhibitList.count;
    } else {
        return _lastSectionArray.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        BannerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"bannerCollectionViewCell" forIndexPath:indexPath];
        NSMutableArray *images = [NSMutableArray array];
        for (HomeBannerModel *model in _bannerArray) {
            [images addObject:model.topicPic];
        }
        cell.shufView.images = images;
        cell.shufView.delegate = self;
        cell.shufView.timeInterval = 5;
        return cell;
    } else if (indexPath.section == 1) {
        HomeLabelListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"homeLabelListCell" forIndexPath:indexPath];
        cell.labelModel = _mainModel.labelList[indexPath.item];
        return cell;
    } else if (indexPath.section == 2 || indexPath.section == 4) {
        HalfImageAndWordsCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"halfImageAndWordsCollectionCell" forIndexPath:indexPath];
        if (indexPath.section == 2) {
            cell.topicModel = _mainModel.topicList[indexPath.item];
        } else {
            cell.exhibitModel = _mainModel.exhibitList[indexPath.item];
        }
        return cell;
    } else if (indexPath.section == 3) {
        HomeSpecialCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"homeSpecialCollectionCell" forIndexPath:indexPath];
        cell.galleryModel = _mainModel.galleryList[indexPath.item];
        return cell;
    } else {
        ExhibitWorkCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"exhibitWorkCollectionCell" forIndexPath:indexPath];
        cell.exhibitWorkModel = _lastSectionArray[indexPath.item];
        return cell;
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 || indexPath.section == 1) {
        return nil;
    } else if (kind == UICollectionElementKindSectionHeader) {
        HeadReusableView *headerV = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headReusableView" forIndexPath:indexPath];
        headerV.titleLabel.text = _headArray[indexPath.section - 2];
        headerV.moreBtn.tag = 100 + indexPath.section;
        [headerV.moreBtn addTarget:self action:@selector(moreBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        return headerV;
    } else {
        return nil;
    }
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_collectionView.contentOffset.y > _lastContentOffset && indexPath.section == 5) {
        CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
        scaleAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 0, 1)];
        scaleAnimation.toValue  = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1)];
        scaleAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        [cell.layer addAnimation:scaleAnimation forKey:@"transform"];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return;
    } else if (indexPath.section == 1) {
        NSString *label = _mainModel.labelList[indexPath.item].label;
        if ([label isEqualToString:@"展览"]) {
            HomeExhibitViewController *exhibitVC = [[HomeExhibitViewController alloc]init];
            [self.navigationController pushViewController:exhibitVC animated:YES];
        } else if ([label isEqualToString:@"作品"]) {
            HomeWorksViewController *worksVC = [[HomeWorksViewController alloc]init];
            [self.navigationController pushViewController:worksVC animated:YES];
        } else if ([label isEqualToString:@"艺术家"]) {
            HomeArtistViewController *artistVC = [[HomeArtistViewController alloc]init];
            [self.navigationController pushViewController:artistVC animated:YES];
        } else if ([label isEqualToString:@"阅读"]) {
            HomeReadViewController *readVC = [[HomeReadViewController alloc]init];
            [self.navigationController pushViewController:readVC animated:YES];
        }
    } else if (indexPath.section == 2) {
        DetailsWebViewController *detailsVC = [[DetailsWebViewController alloc]init];

        detailsVC.urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"discovery/v3/selectTopicDetailInfo"] andParams:@{@"scourceTable": @"topic", @"token": [NSString getUserDefaultToken], @"clientType": @"1", @"topicId": [NSString stringWithFormat:@"%@", _mainModel.topicList[indexPath.item].idField], @"topicType": @"4"}];
        [self.navigationController pushViewController:detailsVC animated:YES];
    } else if (indexPath.section == 3) {
        DetailsWebViewController *detailsVC = [[DetailsWebViewController alloc]init];
        
        detailsVC.urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"discovery/v3/selectTopicDetailInfo"] andParams:@{@"scourceTable": @"gallery", @"token": [NSString getUserDefaultToken], @"clientType": @"1", @"topicId": [NSString stringWithFormat:@"%@", _mainModel.galleryList[indexPath.item].idField], @"topicType": @"4"}];
        [self.navigationController pushViewController:detailsVC animated:YES];
    } else if (indexPath.section == 4) {
        ExhibitDetailsViewController *detailsVC = [[ExhibitDetailsViewController alloc]init];
        detailsVC.urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"exhibit", [NSString stringWithFormat:@"%@", _mainModel.exhibitList[indexPath.item].idField]] andParams:@{@"token": [NSString getUserDefaultToken]}];
        [self.navigationController pushViewController:detailsVC animated:YES];
    } else {
        ExhibitWorkDetailsViewController *detailsVC = [[ExhibitWorkDetailsViewController alloc]init];
        detailsVC.urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"exhibit/WorkDetailV4", [NSString stringWithFormat:@"%@", [_lastSectionArray[indexPath.item]idField]]] andParams:@{@"token": [NSString getUserDefaultToken], @"userId": [NSString getUserDefaultId], @"workID": [NSString stringWithFormat:@"%@", [_lastSectionArray[indexPath.item]idField]]}];
        [self.navigationController pushViewController:detailsVC animated:YES];
    }
        
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    _lastContentOffset = scrollView.contentOffset.y;
}
#pragma mark - flow layout delegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH / 1.8);
    } else if (indexPath.section == 1) {
        return CGSizeMake(SCREEN_WIDTH / 4, 120);
    } else if (indexPath.section == 2) {
        return CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH / 3.8);
    } else if (indexPath.section == 3){
        return CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH / 3);
    } else if (indexPath.section == 4) {
        return CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH / 2);
    } else {
        return CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH * 0.85 + 80);
    }
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 5;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (section == 0 || section == 1) {
        return CGSizeZero;
    }
    return CGSizeMake(SCREEN_WIDTH, 60);
}

#pragma mark - shufView delegate 轮播图cell
- (void)collectionView:(UICollectionView *)collectionView shufSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    HomeBannerDetailsController *detailsVC = [[HomeBannerDetailsController alloc]init];
    if ([_bannerArray[indexPath.item % _bannerArray.count].topicType isEqual:@3]) {
        detailsVC.webString = _bannerArray[indexPath.item % _bannerArray.count].marketingDesc;
    } else if ([_bannerArray[indexPath.item % _bannerArray.count].topicType isEqual:@4]) {
        HomeBannerModel *model = _bannerArray[indexPath.item % _bannerArray.count];
        detailsVC.urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"discovery/v3/selectTopicDetailInfo"] andParams:@{@"token": [NSString getUserDefaultToken], @"topicId": [NSString stringWithFormat:@"%@", model.idField], @"topicType": [NSString stringWithFormat:@"%@", model.topicType]}];
    }
    [self.navigationController pushViewController:detailsVC animated:YES];
}

#pragma mark - button 点击方法
- (void)moreBtnAction:(UIButton *)button
{
    if (button.tag == 102) {
        TopicHeadMoreViewController *headMoreVC = [[TopicHeadMoreViewController alloc]init];
        [self.navigationController pushViewController:headMoreVC animated:YES];
    } else if (button.tag == 103) {
        GalleryHeadMoreViewController *headMoreVC = [[GalleryHeadMoreViewController alloc]init];
        [self.navigationController pushViewController:headMoreVC animated:YES];
    } else if (button.tag == 104) {
        ExhibitHeadMoreViewController *headMoreVC = [[ExhibitHeadMoreViewController alloc]init];
        [self.navigationController pushViewController:headMoreVC animated:YES];
    } else if (button.tag == 105) {
        ExhibitWorkHeadMoreViewController *headMoreVC = [[ExhibitWorkHeadMoreViewController alloc]init];
        [self.navigationController pushViewController:headMoreVC animated:YES];
    }
}
#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
